<template>
    <div>
        <el-button size="small" type="primary" :icon="DocumentAdd" @click="handleAdd" :disabled="add">新增</el-button>
        <el-button size="small" type="primary" :icon="EditPen" @click="dialogEmit" :disabled="update">编辑</el-button>
        <el-button size="small" type="primary" :icon="FolderChecked" :disabled="butShow"
            @click="addDept()">保存</el-button>
        <el-button size="small" type="primary" :icon="CircleClose" :disabled="butShow"
            @click="dialogCancel">取消</el-button>
        <el-form :inline="true" ref="formRef" class="mb-[-16px] mt-4">
            <el-form-item prop="isValid" label="是否有效">
                <el-select v-model="formData.flowNode.isValid" clearable class="w-[775px]" :disabled="disabled">
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                </el-select>
            </el-form-item>
            <el-form-item prop="isFlow" label="启用流程">
                <el-select v-model="formData.flowNode.isFlow" clearable :disabled="disabled" class="w-[310px]">
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                </el-select>
            </el-form-item>
            <el-form-item prop="isBackNode" label="提交至退回节点">
                <el-select v-model="formData.flowNode.isBackNode" clearable :disabled="disabled" class="w-[310px]">
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                </el-select>
            </el-form-item>
            <el-form-item prop="name" label="更新用户">
                <el-input v-model="formData.flowNode.updateUserName" class="w-[310px]" disabled />
            </el-form-item>
            <el-form-item prop="name" label="更新时间">
                <el-input v-model="formData.flowNode.updateTime" class="w-[310px]" disabled />
            </el-form-item>
        </el-form>
        <el-table class="mt-4" size="large" :data="tableData">
            <el-table-column label="序号" type="index" width="60" align="center" prop="number" />
            <el-table-column label="节点名称" prop="nodeName " min-width="100" align="center">
                <template v-slot="scope">
                    <div v-if="scope.$index === 0 || scope.row === tableData[tableData.length - 1]">
                        {{ scope.row.nodeName }}
                    </div>
                    <el-input v-else v-model="scope.row.nodeName" :disabled="disabled" />
                </template>
            </el-table-column>
            <el-table-column label="人员类型" prop="personnelType" min-width="80" align="center">
                <template v-slot="scope">
                    <span v-if="scope.length !== 0">
                        <el-select :disabled="disabled" v-model="scope.row.personnelType" placeholder="请选择"
                            @change="handleNodeChange(scope.row, scope.$index)" v-show="scope.$index !== 0 && scope.row !== tableData[tableData.length - 1]
                                ">
                            <el-option v-for="item in nodeOptions" :key="item.id" :label="item.type"
                                :value="item.type" />
                        </el-select>
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="允许编辑" prop="isEdit " min-width="80" align="center">
                <template v-slot="scope">
                    <el-checkbox :disabled="disabled" v-model="scope.row.isEdit" size="large"
                        v-show="scope.$index !== 0 && scope.row !== tableData[tableData.length - 1]" />
                </template>
            </el-table-column>
            <el-table-column label="审核人员" prop="roleIds" min-width="160" align="center">
                <template v-slot="scope">
                    <el-input :disabled="disabled" v-model="scope.row.roleIds"
                        @click="handleAuditor(scope.row, scope.$index)"
                        v-show="scope.$index !== 0 && scope.row !== tableData[tableData.length - 1]" />
                </template>
            </el-table-column>
            <el-table-column label="下一步流程" prop="nextStep" min-width="80" align="center">
                <template v-slot="scope">
                    <div v-if="scope.row !== tableData[tableData.length - 1]">
                        {{ scope.$index + 2 }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right" align="center">
                <template v-slot="scope">
                    <el-button @click="moveRow(tableData, scope.row, scope.$index, 'up')" size="mini" type="text"
                        :icon="Top" v-show="scope.$index !== 0 && scope.row !== tableData[tableData.length - 1]">
                    </el-button>
                    <el-button @click="moveRow(tableData, scope.row, scope.$index, 'down')" size="mini" type="text"
                        :icon="Bottom" v-show="scope.$index !== 0 && scope.row !== tableData[tableData.length - 1]">
                    </el-button>
                    <el-button size="mini" type="text" :icon="DocumentAdd" @click="onAddItem(scope.row, scope.$index)"
                        v-if="scope.row !== tableData[tableData.length - 1]"></el-button>
                    <div v-else></div>
                    <el-button size="mini" type="text" :icon="Close"
                        v-show="scope.$index !== 0 && scope.row !== tableData[tableData.length - 1]"
                        @click="deleteRow(scope.row)">
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 新增弹窗 -->
        <el-dialog v-model="dialogAdd" title="新增流程" style="width: 400px">
            <el-form class="mb-[-16px]" :inline="true">
                <el-form-item label="复制流程" :label-width="formLabelWidth">
                    <el-select v-model="a" class="w-[400px]">
                        <el-option label="Zone No.1" value="shanghai" />
                        <el-option label="Zone No.2" value="beijing" />
                    </el-select>
                    <span class="ml-2" style="color: #409eff" @click="dialogAdd = false">不需要复制</span>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleSubmit">确定</el-button>
                    <el-button type="primary" @click="dialogAdd = false"> 取消 </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 用户角色弹窗 -->
        <el-dialog v-model="auditorAdd" title="用户角色" style="width: 400px">
            <div>
                <el-transfer v-model="selectedValues" :data="dataList" :titles="['角色', '结果列表']" filterable />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="auditorAddSubmit">确定</el-button>
                    <el-button type="primary" @click="auditorAdd = false"> 取消 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="flow">
import { deptJobList, deptRoleList, deptUsersList, flowAdd } from '@/api/deptFlow'
import {
    DocumentAdd,
    EditPen,
    FolderChecked,
    CircleClose,
    Top,
    Bottom,
    Close
} from '@element-plus/icons-vue'
import { defineProps } from 'vue'
import { reactive } from 'vue'
interface Option {
    key: number
    label: string
}
const disabled = ref(true)
const dataList = ref([])

const selectedValues = ref([]) // 选中的 B 列表数据

const auditorAddSubmit = () => {
    const selectedItems = dataList.value.filter((item) => selectedValues.value.includes(item.key))
    tableData.value[auditorId.value].roleIds = selectedItems.map((item) => item.label).join(', ')
    auditorAdd.value = false
}
// 定义接收的 props----------------------------------
const props = defineProps({
    formData: {
        type: Object,
        required: true
    },
    isAdd: {
        type: String,
        required: true
    },
    formTitle: {
        type: String,
        required: true
    }
})
const butShow = ref(true)
const dialogAdd = ref(false)
const auditorAdd = ref(false)
const add = ref(false)
const update = ref(false)
const auditorId = ref(0)
const formData = reactive({
    depId: '',
    type: '',
    proposalType: '',
    configProposal: '',
    isBasics: '',
    flowNode: {
        isValid: '是',
        proposalType: '',
        isFlow: '是',
        isBackNode: '是',
        updateTime: '',
        updateUserName: ''
    },
    nodes: []
})

const tableData = ref([
    { nodeName: '启动流程', personnelType: '', isEdit: '', number: '', roleIds: '', nextStep: '2' },
    { nodeName: '结束', personnelType: '', isEdit: '', number: '', roleIds: '', nextStep: '0' }
])
const nodeOptions = [
    {
        type: '用户',
        id: 1
    },
    {
        type: '角色',
        id: 2
    },
    {
        type: '岗位',
        id: 3
    }
]
const handleNodeChange = (val: any, index: number) => {

    tableData.value[index].roleIds = []
    selectedValues.value = []
    SelChrGate(val.personnelType)
}

const addDept = async () => {
    console.log(tableData, 'tableData')
    formData.nodes = tableData.value
    const data = await flowAdd({
        formData
    })

}

const load = async () => {
    if (props.isAdd) {
        add.value = false
        update.value = true
    } else {
        update.value = false
        add.value = true
    }
    formData.type = props.formData.type
    formData.depId = props.formData.depId
    formData.proposalType = props.formData.proposalType
    formData.isBasics = props.formData.isBasics
    formData.configProposal = props.formData.proposal
    formData.flowNode.proposalType = props.formTitle
}
load()
//调用用户角色接口
const SelChrGate = async (type: string) => {
    if (type === '用户') {
        const listData = await deptUsersList()
        selectedValues.value = []

        dataList.value = listData.map((item: any) => ({
            key: item.id,
            label: item.username
        }))
        console.log('a', listData)
    }
    if (type === '角色') {
        const listData = await deptRoleList()
        selectedValues.value = []

        dataList.value = listData.map((item: any) => ({
            key: item.id,
            label: item.name
        }))
    }
    if (type === '岗位') {
        const listData = await deptJobList()
        selectedValues.value = []

        dataList.value = listData.map((item: any) => ({
            key: item.id,
            label: item.username
        }))
    }
}
const handleAuditor = (value: any, index: number) => {
    auditorAdd.value = true
    auditorId.value = index
    selectedValues.value = []
    SelChrGate(value.personnelType)

}
const handleAdd = () => {
    disabled.value = false
    butShow.value = false
    add.value = true
}

const onAddItem = (val: any, index: number) => {

    const newRow = {
        nodeName: '',
        personnelType: '用户',
        isEdit: true,
        number: index + 2,
        roleIds: '',
        nextStep: index + 3
    }
    tableData.value.splice(tableData.value.length - 1, 0, newRow)
}
const handleSubmit = () => { }
const dialogEmit = () => {
    butShow.value = false
}
const deleteRow = (row: any) => {
    // 删除当前行
    const index = tableData.value.indexOf(row)
    if (index !== -1) {
        tableData.value.splice(index, 1)
    }
}
const dialogCancel = () => {
    butShow.value = true
}
const moveRow = (tabeldate: any, row: any, index: any, direction: string) => {
    // 计算目标索引
    const targetIndex = direction === 'up' ? index - 1 : index + 1

    // 边界判断
    if (targetIndex < 1 || targetIndex >= tabeldate.length - 1) return

    // 移动数据
    const temp = tabeldate[index]
    tabeldate[index] = tabeldate[targetIndex]
    tabeldate[targetIndex] = temp

    tableData.value.forEach((rowData, idx) => {
        rowData.number = (idx + 1).toString();  // 重新设置序号
        console.log(tableData.value.length, rowData.number)
        if (Number(rowData.number) !== tableData.value.length) {
            rowData.nextStep = (idx + 2).toString()
        }

    });
    console.log(tableData.value.map(o => { return o.nextStep }), '333')
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}
</script>

<style scoped>
.el-transfer {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
}
</style>
